package com.meiya.hugegraph.controller;

import com.meiya.hugegraph.api.HugeGraphManager;
import com.meiya.hugegraph.entity.dto.TransactionSearchParam;
import com.meiya.hugegraph.entity.vo.ApiResponse;
import com.meiya.hugegraph.entity.vo.BatchResult;
import com.meiya.hugegraph.entity.vo.EdgeVO;
import com.meiya.hugegraph.entity.vo.VertexVO;
import com.meiya.hugegraph.service.TransactionOperations;
import org.apache.hugegraph.structure.constant.Direction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 交易图数据REST API控制器
 * 提供交易图数据的RESTful接口
 */
@RestController
@RequestMapping("/api/transaction")
public class TransactionController {

    private static final Logger logger = LoggerFactory.getLogger(TransactionController.class);

    @Resource
    private HugeGraphManager graphManager;

    @Resource
    private TransactionOperations transOps;

    /**
     * 查询持卡人的卡
     *
     * @param holderName 持卡人姓名
     * @param limit      限制数量
     *
     * @return 卡顶点列表
     */
    @GetMapping("/cards")
    public ResponseEntity<ApiResponse<List<VertexVO>>> getCardsByHolder(
            @RequestParam(required = false) String holderName,
            @RequestParam(defaultValue = "10") int limit) {

        try {
            // 调用服务方法获取数据
            List<VertexVO> result = transOps.convertVerticesToVO(
                    transOps.getCards(holderName, limit));

            return ResponseEntity.ok(new ApiResponse<>(true, "查询成功", result));
        } catch (Exception e) {
            logger.error("查询卡信息失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<>(false, "查询失败: " + e.getMessage(), null));
        }
    }

    /**
     * 查询卡的交易
     *
     * @param cardId    卡ID
     * @param direction 方向(IN, OUT, BOTH)
     * @param limit     限制数量
     *
     * @return 交易边列表
     */
    @GetMapping("/cards/{cardId}/transactions")
    public ResponseEntity<ApiResponse<List<EdgeVO>>> getCardTransactions(
            @PathVariable Object cardId,
            @RequestParam(defaultValue = "BOTH") String direction,
            @RequestParam(defaultValue = "10") int limit) {

        try {
            Direction dir = Direction.valueOf(direction.toUpperCase());
            List<String> labels = Collections.singletonList("transaction");

            // 调用服务方法获取数据
            List<EdgeVO> result = transOps.convertEdgesToVO(
                    transOps.getTransactionsOfVertex(cardId, dir, labels, limit));

            return ResponseEntity.ok(new ApiResponse<>(true, "查询成功", result));
        } catch (Exception e) {
            logger.error("查询交易信息失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<>(false, "查询失败: " + e.getMessage(), null));
        }
    }

    /**
     * 查询金额大于等于指定值的交易
     *
     * @param minAmount 最小金额
     * @param limit     限制数量
     *
     * @return 交易边列表
     */
    @GetMapping("/transactions")
    public ResponseEntity<ApiResponse<List<EdgeVO>>> getTransactions(
            @RequestParam(required = false) Double minAmount,
            @RequestParam(defaultValue = "10") int limit) {

        try {
            // 调用服务方法获取数据
            List<EdgeVO> result = transOps.convertEdgesToVO(
                    transOps.getTransactions(minAmount, limit));

            return ResponseEntity.ok(new ApiResponse<>(true, "查询成功", result));
        } catch (Exception e) {
            logger.error("查询交易信息失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<>(false, "查询失败: " + e.getMessage(), null));
        }
    }

     /**
     * 根据卡号集合查询相关交易
     *
     * @param queryParam 查询参数，包含cards(卡号集合)、hop(跳数)、limit(限制条数)
     * @return 交易数据列表
     */
    @PostMapping("/transactions/search")
    public ResponseEntity<ApiResponse<Map<String, Object>>> searchTransactionsByCards(
            @RequestBody TransactionSearchParam queryParam) {
        
        if (queryParam.getCards() == null || queryParam.getCards().isEmpty()) {
            return ResponseEntity.badRequest()
                    .body(new ApiResponse<>(false, "卡号集合不能为空", null));
        }
        
        try {
            // 调用服务方法查询数据
            int hop = Math.max(1, queryParam.getHop()); // 确保至少为1跳
            int limit = Math.max(1, queryParam.getLimit()); // 确保至少返回1条记录
            
            logger.info("根据卡号集合查询交易，卡号数量: {}，跳数: {}，限制条数: {}", 
                    queryParam.getCards().size(), hop, limit);
            
            Map<String, Object> result = transOps.searchTransactionsByCards(
                    queryParam.getCards(), hop, limit);
            
            return ResponseEntity.ok(new ApiResponse<>(true, "查询成功", result));
        } catch (Exception e) {
            logger.error("查询交易数据失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<>(false, "查询失败: " + e.getMessage(), null));
        }
    }

    /**
     * 上传CSV文件批量创建交易数据（包括卡和交易）
     *
     * @param file CSV文件(列: jykh,jyhm,jyje,jysj,dskh,dshm,ukey)
     *
     * @return 批量创建结果
     */
    @PostMapping("/transaction-data/upload")
    public ResponseEntity<ApiResponse<BatchResult>> uploadTransactionData(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ResponseEntity.badRequest()
                    .body(new ApiResponse<>(false, "请选择要上传的文件", null));
        }

        try {
            // 调用服务方法上传完整交易数据
            BatchResult result = transOps.uploadTransactionData(file);
            return ResponseEntity.ok(new ApiResponse<>(true, "批量创建交易数据成功", result));
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest()
                    .body(new ApiResponse<>(false, e.getMessage(), null));
        } catch (Exception e) {
            logger.error("批量创建交易数据失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<>(false, "批量创建交易数据失败: " + e.getMessage(), null));
        }
    }

    /**
     * 使用原生Java API上传CSV文件批量创建交易数据（包括卡和交易）
     *
     * @param file CSV文件(列: jykh,jyhm,jyje,jysj,dskh,dshm,ukey)
     *
     * @return 批量创建结果
     */
    @PostMapping("/transaction-data/upload-native")
    public ResponseEntity<ApiResponse<BatchResult>> uploadTransactionDataNative(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ResponseEntity.badRequest()
                    .body(new ApiResponse<>(false, "请选择要上传的文件", null));
        }

        try {
            // 调用服务方法使用原生API上传交易数据
            BatchResult result = transOps.uploadTransactionDataNative(file);
            return ResponseEntity.ok(new ApiResponse<>(true, "使用原生API批量创建交易数据成功", result));
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest()
                    .body(new ApiResponse<>(false, e.getMessage(), null));
        } catch (Exception e) {
            logger.error("使用原生API批量创建交易数据失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<>(false, "使用原生API批量创建交易数据失败: " + e.getMessage(), null));
        }
    }

    /**
     * 删除卡
     *
     * @param cardId 卡ID
     *
     * @return 操作结果
     */
    @DeleteMapping("/cards/{cardId}")
    public ResponseEntity<ApiResponse<Void>> deleteCard(@PathVariable Object cardId) {
        try {
            boolean success = graphManager.removeVertex(cardId);
            if (success) {
                return ResponseEntity.ok(new ApiResponse<>(true, "删除成功", null));
            } else {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body(new ApiResponse<>(false, "卡不存在", null));
            }
        } catch (Exception e) {
            logger.error("删除卡失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<>(false, "删除失败: " + e.getMessage(), null));
        }
    }

    /**
     * 删除交易
     *
     * @param transactionId 交易ID
     *
     * @return 操作结果
     */
    @DeleteMapping("/transactions/{transactionId}")
    public ResponseEntity<ApiResponse<Void>> deleteTransaction(@PathVariable String transactionId) {
        try {
            boolean success = graphManager.removeEdge(transactionId);
            if (success) {
                return ResponseEntity.ok(new ApiResponse<>(true, "删除成功", null));
            } else {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body(new ApiResponse<>(false, "交易不存在", null));
            }
        } catch (Exception e) {
            logger.error("删除交易失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse<>(false, "删除失败: " + e.getMessage(), null));
        }
    }

}
